#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

int array[8] = {3, 1, 2, 4, 5, 6, 7, 0};

struct param
{
    int start;
    int end;
};

void *sort(void *arg)
{
    struct param *param;
    param=(struct param *)arg;
    for(int i=param->start;i<param->end-1;i++)
    {
        int min=i;
        for(int j=i+1;j<param->end;j++)
        {
            if(array[j]<array[min])
            {
                min=j;
            }
        }
        int temp;
        temp=array[i];
        array[i]=array[min];
        array[min]=temp;
    }
    return NULL;
}

void merge(int source[],int temp[],int start,int end)
{
    int i=start,j=(start+end)/2,k=start;
    while(i!=(start+end)/2 && j!=end)
    {
        if(source[i]>source[j])
        {
            temp[k++]=source[j++];
        }
        else
        {
            temp[k++]=source[i++];
        }
    }
    while(i!=(start+end)/2)
    {
        temp[k++]=source[i++];
    }
    while(j!=end)
    {
        temp[k++]=source[j++];
    }
    for(int i=start;i<end;i++)
    {
        source[i]=temp[i];
    }
}

int main()
{
    pthread_t worker[2];
    struct param params[2];
    int len=sizeof(array)/sizeof(int);
    int NR_CHILD=len/2;
    for(int i=0;i<2;i++)
    {
        struct param *param;
        param=&params[i];
        param->start=i*NR_CHILD;
        param->end=(i+1)*NR_CHILD;
        pthread_create(&worker[i],NULL,sort,param);
    }
    for(int i=0;i<2;i++)
    {
        pthread_join(worker[i],NULL);
    }
    int t[len];
    merge(array,t,0,len);
    for(int i=0;i<len;i++)
    {
        printf("%d\n",array[i]);
    }
    return 0;
}
